package com.shiroa.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.shiroa.entity.SysMenu;
import com.shiroa.entity.SysRole;
import com.shiroa.entity.SysUser;
import com.shiroa.security.UserDetailslmpl;
import com.shiroa.service.ISysMenuService;
import com.shiroa.service.ISysRoleService;
import com.shiroa.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Component
public class PermService implements UserDetailsService {
    @Autowired
    ISysUserService iSysUserService;
    @Autowired
    ISysRoleService sysRoleService;
    @Autowired
    ISysMenuService iSysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user = iSysUserService.getOne(Wrappers.lambdaQuery(SysUser.class).eq(SysUser::getUserName, username));
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        UserDetailslmpl userDetailslmpl = new UserDetailslmpl();
        userDetailslmpl.setUsername(user.getUserName());
        userDetailslmpl.setPassword(user.getPassword());
        userDetailslmpl.setNickName(user.getNickName());
        List<SysRole> list =sysRoleService.getAllByUsername(user.getUserName());
        List<Long> roleIdList = list.stream().mapToLong(SysRole::getRoleId).boxed().collect(Collectors.toList());
        List<SysMenu> menuList = iSysMenuService.getByRoleIdList(roleIdList);
        Set<String> roleNames = list.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
        Set<String> permeList = menuList.stream().filter(item -> StringUtils.hasText(item.getPerms()))
                .map(SysMenu::getPerms).collect(Collectors.toSet());
        userDetailslmpl.setPermsList(permeList);
        userDetailslmpl.setRolesName(roleNames);
        return userDetailslmpl;
    }
}
